import bcrypt
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from fastapi import Form,Request
from starlette.responses import FileResponse
from starlette.responses import RedirectResponse
from database import get_user, get_logging, create_table_login_data, insert_login_data, get_login_data, get_information, get_client_ip,insert_user_data
from pydantic import BaseModel
from bcrypt import hashpw, gensalt
from device import clinent_modbus

router = APIRouter()  # 创建一个路由器实例

@router.get("/login")
async def login():
    return FileResponse('static/login.html')

@router.post("/login")
async def login_post(request: Request,username: str = Form(...), password: str = Form(...)):
    create_table_login_data()
    ip_address = get_client_ip(request)
    #将读到的密码字符串用同款编码转换为字节串格式
    byte_hashed_password = get_user(username)['Password'].encode('utf-8')
    # 将用户输入的密码编码为字节串
    password_bytes = password.encode('utf-8')
    # 使用 checkpw 验证密码
    is_match = bcrypt.checkpw(password_bytes, byte_hashed_password)

    # 根据验证结果执行操作
    if is_match:
        insert_login_data(username, ip_address, 'successful')
        return RedirectResponse(url=f"/login/{username}")
    else:
        class LoginError(BaseModel):
            message: str
            status_code: int = 400

        insert_login_data(username, ip_address, 'failed')
        error = LoginError(message="用户不存在或密码错误")
        return JSONResponse(status_code=error.status_code, content=error.dict())

@router.post("/register/")
async def register(
        username: str = Form(...),
        password: str = Form(...),
        email: str = Form(None),
        phone: str = Form(None),
        role: int = Form(...),
):
    # 对密码进行哈希处理
    hashed_password = hashpw(password.encode('utf-8'), gensalt(10))
    insert_user_data(username, hashed_password, email, phone, role)
    # 如果保存成功，可以返回一个成功的响应
    return FileResponse('static/user.html')

@router.post("/login/{username}")
async def login_user(username: str):
    return FileResponse('static/menu.html')


@router.post("/data")
async def data():
    info = get_information(get_login_data()['username'])
    return info


@router.post("/data1")
@router.get("/data1")
async def data1():
    info = get_logging()
    return info

@router.get("/")
async def index():
    return RedirectResponse("/login")

@router.post("/modbus")
@router.get("/modbus")
async def modbusModel(
    device: str = Form(...),
    ip: str = Form(...),
    port: str = Form(...),
    start: int = Form(...),
    count: int = Form(...)
 ):
    print(device, ip, port, start, count)
    try:
        clinent_modbus(device, ip, port, start, count)
        # 如果处理成功，返回一个成功的响应
        # 注意：这里返回的是一个 HTML 文件，确保 'static/user.html' 路径正确
        return clinent_modbus(device, ip, port, start, count)
    except Exception as e:
        # 如果发生异常，抛出一个 HTTP 异常
        raise HTTPException(status_code=400, detail=f"Modbus operation failed: {str(e)}")

# 定义一个 Pydantic 模型来验证表单数据
class RegisterRequest(BaseModel):
    username: str
    password: str
    email: str | None = None
    phone: str | None = None
    role: int

def get_routes():
    return router